package com.agri.service.impl;

import com.agri.entity.CropPriceTrend;
import com.agri.mapper.CropPriceTrendMapper;
import com.agri.result.Result;
import com.agri.service.PriceTrendService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 价格趋势服务实现类
 * 处理农产品价格趋势分析和预测功能
 *
 * @author Agri-Fin-Sale Team
 * @since 2025-11-05
 */
@Service
public class PriceTrendServiceImpl implements PriceTrendService {
    @Autowired
    private CropPriceTrendMapper cropPriceTrendMapper;

    @Override
    public Result<?> getCropPriceTrend(Long cropId, Date startDate, Date endDate) {
        QueryWrapper<CropPriceTrend> wrapper = new QueryWrapper<>();
        wrapper.eq("crop_id", cropId)
               .orderByAsc("price_date");

        if (startDate != null) {
            wrapper.ge("price_date", startDate);
        }
        if (endDate != null) {
            wrapper.le("price_date", endDate);
        }

        // 如果没有指定日期范围，默认查询最近30天的数据
        if (startDate == null && endDate == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -30);
            wrapper.ge("price_date", calendar.getTime());
        }

        List<CropPriceTrend> trends = cropPriceTrendMapper.selectList(wrapper);
        return Result.success(trends);
    }

    @Override
    public Result<?> getLatestPrice(Long cropId) {
        QueryWrapper<CropPriceTrend> wrapper = new QueryWrapper<>();
        wrapper.eq("crop_id", cropId)
               .orderByDesc("price_date")
               .last("LIMIT 1");

        CropPriceTrend latestPrice = cropPriceTrendMapper.selectOne(wrapper);
        if (latestPrice == null) {
            return Result.fail("未找到该农产品的价格数据");
        }
        return Result.success(latestPrice);
    }

    @Override
    public Result<?> predictPrice(Long cropId) {
        // 这里简化处理，实际应该调用AI预测模型
        // 返回一个模拟的预测结果
        QueryWrapper<CropPriceTrend> wrapper = new QueryWrapper<>();
        wrapper.eq("crop_id", cropId)
               .orderByDesc("price_date")
               .last("LIMIT 7"); // 获取最近7天的数据

        List<CropPriceTrend> recentPrices = cropPriceTrendMapper.selectList(wrapper);
        if (recentPrices.isEmpty()) {
            return Result.fail("数据不足，无法进行价格预测");
        }

        // 简单预测：基于最近价格的平均值
        double sum = 0;
        for (CropPriceTrend trend : recentPrices) {
            sum += trend.getMarketPrice().doubleValue();
        }
        double predictedPrice = sum / recentPrices.size();

        return Result.success(String.format("预测价格: %.2f 元/公斤 (基于最近%d天数据)",
            predictedPrice, recentPrices.size()));
    }
}